package tas.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import tas.dao.DaoTerminal;
import tas.dao.impl.DaoTerminalImpl;
import tas.domain.Terminal;
import tas.xml.Xml;

@WebServlet(name = "ServletTerminales", urlPatterns = {"/view/admin/Terminales"})
public class ServletTerminales extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String autorizacion = (String) request.getSession().getAttribute("autorizacion");
        String ID = (String) request.getSession().getAttribute("ID");

        if ((ID == null) || (autorizacion == null)
                || (!autorizacion.equals("ADMIN"))
                || (!ID.equals(request.getSession().getId()))) {

            response.sendRedirect("../");

        } else {

            request.setCharacterEncoding("UTF-8");
            String accion = request.getParameter("accion");
            String result = null;
            String contentType = "text/html;charset=UTF-8";
            //
            DaoTerminal daoTerminal = new DaoTerminalImpl();

            if (accion == null) {
                result = "Solicitud no recibida";

            } else if (accion.equals("INI")) {
                RequestDispatcher dispatcher = request.getRequestDispatcher("terminales.jsp");
                dispatcher.forward(request, response);

            } else if (accion.equals("QRY")) {
                String estado = request.getParameter("estado");
                String ip = request.getParameter("ip");
                String marca = request.getParameter("marca");

                String filtro = "";

                if (ip.trim().length() > 0) {
                    filtro += " (TER.IPTERMINAL='" + ip + "')";
                } else if (marca.trim().length() > 0) {
                    filtro += " (UPPER(TER.MARCATERMINAL) like UPPER('%" + marca + "%'))";
                } else {
                    filtro = "(TER.ESTADOTERMINAL='" + estado + "')";
                }

                List<Object[]> list = daoTerminal.TerminalQRY(filtro);

                if (list != null) {
                    if (list.isEmpty()) {
                        result = "Consulta no tiene resultados";
                    } else {
                        StringBuilder sb = new StringBuilder();

                        for (Object[] f : list) {
                            sb.append("<tr>");
                            sb.append("<th>").append("<input type=\"radio\" value=\"").append(f[0]).append("\" name=\"_upd\"/>").append("</th>");
                            sb.append("<td>").append(f[1]).append("</td>");
                            sb.append("<td>").append(f[2]).append("</td>");
                            sb.append("<td>").append(f[3]).append("</td>");
                            sb.append("<td>").append(f[4]).append("</td>");
                            sb.append("<td>").append(f[5]).append("</td>");
                            sb.append("<td>").append(f[6]).append("</td>");
                            sb.append("<td>").append(f[7]).append("</td>");
                            sb.append("</tr>");
                        }

                        result = "Ok!" + sb.toString();
                    }
                } else {
                    result = "Consulta no puede ser atendida";
                }

            } else if (accion.equals("INS")) {

                Terminal t = new Terminal();
                result = valida(request, t);

                if (result == null) {
                    result = daoTerminal.TerminalINS(t);
                }

            } else if (accion.equals("GET")) {
                String id = request.getParameter("id");
                Integer idx = null;

                if (id != null) {
                    try {
                        idx = Integer.valueOf(id);
                    } catch (NumberFormatException e) {
                        result = "Valor errado de idterminal";
                    }
                } else {
                    result = "ID Terminal no recibido";
                }

                if (result == null) {
                    Terminal t = daoTerminal.TerminalGET(idx);

                    if (t != null) {

                        Object[] ftit = {
                            "idterminal_upd", "idestado", "descripcion_upd", "idtipo_upd",
                            "ip_upd", "mac_upd", "marca_upd",
                            "modelo_upd", "idestado"
                        };
                        Object[] fdat = {
                            t.getIDTERMINAL(), t.getESTADOTERMINAL(), t.getDESCRIPCIONTERMINAL(), t.getIDTIPO(),
                            t.getIPTERMINAL(), t.getMACADDTERMINAL(), t.getMARCATERMINAL(),
                            t.getMODELOTERMINAL(), t.getESTADOTERMINAL()
                        };

                        List<Object[]> list = new LinkedList<Object[]>();
                        list.add(ftit);
                        list.add(fdat);

                        Xml xml = new Xml();
                        StringBuilder data = xml.toXml(list);
                        result = data.toString();

                        contentType = "text/xml;charset=UTF-8";
                    }
                }
            } else if (accion.equals("DEL")) {

            } else if (accion.equals("UPD")) {
                Terminal t = new Terminal();
                result = valida(request, t);

                if (result == null) {
                    result = daoTerminal.TerminalUPD(t);
                }
            } else {
                result = "Solicitud no reconocida";
            }

            if (result == null) {
                result = ""; // por ajax, para que regrese a mismo JSP
            }

            response.setContentType(contentType);
            PrintWriter out = response.getWriter();
            out.print(result);
            out.close();
        }
    }

    private String valida(HttpServletRequest request, Terminal terminal) {
        String error = "<ul>";
        String idterminal = request.getParameter("idterminal");
        String descripcionterminal = request.getParameter("descripcionterminal");
        String idtipo = request.getParameter("idtipo");
        String ipterminal = request.getParameter("ipterminal");
        String macaddterminal = request.getParameter("macaddterminal");
        String marcaterminal = request.getParameter("marcaterminal");
        String modeloterminal = request.getParameter("modeloterminal");
        //String estadoterminal = request.getParameter("estadoterminal");

        Integer idterminalx = null;
        if (idterminal != null) {
            try {
                idterminalx = Integer.valueOf(idterminal);
            } catch (NumberFormatException e) {
                error += "<li>Valor errado de idterminal</li>";
            }
        }

        if ((descripcionterminal == null)
                || (descripcionterminal.trim().length() == 0)) {
            error += "<li>Descripción incorrecta</li>";
        }

        Integer idtipox = null;
        if (idtipo != null) {
            try {
                idtipox = Integer.valueOf(idtipo);
            } catch (NumberFormatException e) {
                error += "<li>Valor errado de idtipo</li>";
            }
        }

        if ((ipterminal == null)
                || (ipterminal.trim().length() == 0)) {
            error += "<li>Ingrese IP del Terminal</li>";
        }

        if (error.equals("<ul>")) {
            terminal.setIDTERMINAL(idterminalx);
            terminal.setDESCRIPCIONTERMINAL(descripcionterminal);
            terminal.setIDTIPO(idtipox);
            terminal.setIPTERMINAL(ipterminal);
            terminal.setMACADDTERMINAL(macaddterminal);
            terminal.setMARCATERMINAL(marcaterminal);
            terminal.setMODELOTERMINAL(modeloterminal);
            terminal.setESTADOTERMINAL("R");
            //terminal.setESTADOTERMINAL(estadoterminal);

            error = null;
        } else {
            error += "</ul>";
        }

        return error;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
